package com.alibaba.easyexcel.test.my;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * @author tianhao.luo@hand-china.com
 */
public class MyHandler extends AbstractMergeStrategy {

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if(relativeRowIndex==null ||relativeRowIndex==0){
            return;
        }
        int rowIndex = cell.getRowIndex();
        int colIndex = cell.getColumnIndex();
        sheet=cell.getSheet();
        Row preRow = sheet.getRow(rowIndex-1);
        if (preRow == null){
            return;
        }
        Cell preCell = preRow.getCell(colIndex);//获取上一行的该格
        Object curData = cell.getCellTypeEnum() == CellType.STRING ? cell.getStringCellValue() : cell.getNumericCellValue();
        Object preData = preCell.getCellTypeEnum() == CellType.STRING ? preCell.getStringCellValue() : preCell.getNumericCellValue();

        if (curData.equals(preData)) {
            System.out.println("合并,"+preRow.getRowNum()+"行的："+preCell.getColumnIndex()+",和"+cell.getRowIndex()+"行的："+cell.getColumnIndex());
        }

        //List<CellRangeAddress> list = sheet.getMergedRegions();
        //CellStyle cs = cell.getCellStyle();
        //cell.setCellStyle(cs);
        //for (CellRangeAddress cellRangeAddress : list) {
        //    if (cellRangeAddress.containsRow(preCell.getRowIndex()) && cellRangeAddress.containsColumn(preCell.getColumnIndex())) {
        //        int lastColIndex = cellRangeAddress.getLastColumn();
        //        int firstColIndex = cellRangeAddress.getFirstColumn();
        //        CellRangeAddress cra = new CellRangeAddress(cell.getRowIndex(), cell.getRowIndex(), firstColIndex, lastColIndex);
        //        sheet.addMergedRegion(cra);
        //        RegionUtil.setBorderBottom(BorderStyle.THIN, cra, sheet);
        //        RegionUtil.setBorderLeft(BorderStyle.THIN, cra, sheet);
        //        RegionUtil.setBorderRight(BorderStyle.THIN, cra, sheet);
        //        RegionUtil.setBorderTop(BorderStyle.THIN, cra, sheet);
        //        return;
        //    }
        //}

    }

}

